//
//  SSCRateToolAdapter.m
//  Unity-iPhone
//
//  Created by xuzepei on 16/4/13.
//
//

#import "SSCRateToolAdapter.h"

@implementation SSCRateToolAdapter

+ (SSCRateToolAdapter*)getInstance
{
    static SSCRateToolAdapter* sharedInstance = nil;
    static dispatch_once_t token;
    
    dispatch_once(&token, ^{
        sharedInstance = [[SSCRateToolAdapter alloc] init];
        [RateTool getInstance].delegate = sharedInstance;
    });
    
    return sharedInstance;
}

- (void)setGameObjectName:(char*)name
{
    if(name && strlen(name))
    {
        self.objectName = [NSString stringWithFormat:@"%s",name];
    }
}

- (void)rateForAppleId:(char*)id alertMessage:(char*)alertMessage
{
    NSString* param0 = @"";
    NSString* param1 = @"";
    
    if(id && strlen(id))
    {
        param0 = [NSString stringWithFormat:@"%s",id];
    }
    
    if(alertMessage && strlen(alertMessage))
    {
        param1 = [NSString stringWithFormat:@"%s",alertMessage];
    }
    
    if([param1 length])
        [RateTool rateForAppleID:param0 alertMessage:param1];
    else
        [RateTool rateForAppleID:param0];
}

- (bool)hasRated
{
    return [RateTool hasRated];
}

- (void)openUrl:(char*)url
{
    NSString* param0 = @"";

    if(url && strlen(url))
    {
        param0 = [NSString stringWithFormat:@"%s",url];
    }
    
    [RateTool openUrl:param0];
}

#pragma mark - RateToolDelegate

- (void)willShowStoreProductViewController
{
    static NSString *methodName = @"willShowStoreProductViewController";
    if([self.objectName length])
    {
        UnitySendMessage([self.objectName UTF8String],[methodName UTF8String],"");
    }
}

- (void)dismissedStoreProductViewController
{
    static NSString *methodName = @"dismissedStoreProductViewController";
    if([self.objectName length])
    {
        UnitySendMessage([self.objectName UTF8String],[methodName UTF8String],"");
    }
}

@end

// When native code plugin is implemented in .mm / .cpp file, then functions
// should be surrounded with extern "C" block to conform C function naming rules
extern "C" {
    
    //To set the name of game object for UnitySendMessage method
    void _SetGameObjectNameForRT(char* gameObjectName)
    {
        [[SSCRateToolAdapter getInstance] setGameObjectName:gameObjectName];
    }
    
    void _RateForID(char* id, char* alterMessage)
    {
        [[SSCRateToolAdapter getInstance] rateForAppleId:id alertMessage:alterMessage];
    }
    
    bool _HasRated()
    {
        return [[SSCRateToolAdapter getInstance] hasRated];
    }
    
    void _OpenUrl(char* url)
    {
        [[SSCRateToolAdapter getInstance] openUrl:url];
    }
}
